/*
 * @(#)ItemSelectionScreen.java	1.6 04/07/12
 *
 * Copyright (c) 2000-2004 Sun Microsystems, Inc. All rights reserved.
 * PROPRIETARY/CONFIDENTIAL
 * Use is subject to license terms
 */

package example.pim;

import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.Event;
import javax.microedition.pim.EventList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;
import javax.microedition.pim.PIMItem;
import javax.microedition.pim.PIMList;
import javax.microedition.pim.ToDo;
import javax.microedition.pim.ToDoList;

/**
 * Demonstrate the use of JSR 75 PIM APIs
 */
public class ItemSelectionScreen extends List implements CommandListener {
    
    private final Command selectCommand = new Command("View", Command.ITEM, 1);
    private final Command backCommand = new Command("Back", Command.BACK, 1);
    private final Command removeCommand = new Command("Delete", Command.SCREEN, 3);
    private final Command newCommand = new Command("New", Command.SCREEN, 2);
    private final Command syncCommand = new Command("Upload to GContacts", Command.OK, 4);
    
    private final PIMDemo midlet;
    private final Displayable caller;
    private final int listType;
    private final PIMList list;
    private final Vector itemList = new Vector();
    
    private boolean[] b;
    private String param;
    private String name;
    private String phone;
    private String email;
    
    public ItemSelectionScreen(PIMDemo midlet, Displayable caller,
            int listType, PIMList list) throws PIMException {
        
        super("Select a PIM item", List.MULTIPLE);
        this.midlet = midlet;
        this.caller = caller;
        this.listType = listType;
        this.list = list;
        
        populateList();
        
        addCommand(backCommand);
        addCommand(newCommand);
        setCommandListener(this);
    }
    
    void populateList() throws PIMException {
        deleteAll();
        removeCommand(selectCommand);
        removeCommand(removeCommand);
        itemList.removeAllElements();
        for (Enumeration items = list.items(); items.hasMoreElements();) {           //paging goes here ...
            PIMItem item = (PIMItem) items.nextElement();
            int fieldCode = 0;
            switch (listType) {
                case PIM.CONTACT_LIST:
                    fieldCode = Contact.FORMATTED_NAME;
                    break;
                case PIM.EVENT_LIST:
                    fieldCode = Event.SUMMARY;
                    break;
                case PIM.TODO_LIST:
                    fieldCode = ToDo.SUMMARY;
                    break;
            }
            String label = getDisplayedField(item);
            if (label == null) {
                label = "<Incomplete data>";
            }
            append(label, null);
            itemList.addElement(item);
        }
        //System.out.println("size = " + size());
        if (size() > 0) {
            setSelectCommand(List.SELECT_COMMAND);
            addCommand(selectCommand);
            addCommand(removeCommand);
            addCommand(syncCommand);
        }
    }
    
    public void commandAction(Command command, Displayable displayable) {
        if (command == backCommand) {
            Display.getDisplay(midlet).setCurrent(caller);
        } else if (command == selectCommand) {
            try {
                b = new boolean[size()];
                int csel = getSelectedFlags(b);
                //System.out.println("count = " + csel);
                if( csel != 1 ) {
                    Alert alert = new Alert("Error", "Please select only one item to view.", null, AlertType.ERROR);
                    alert.setTimeout(Alert.FOREVER);
                    Display.getDisplay(midlet).setCurrent(alert, this);
                    return;
                }
                for( int i = 0; i < b.length; i++ ) {
                    if( !b[i] )
                        continue;
                    PIMItem item = (PIMItem) itemList.elementAt(i);
                    Displayable screen = new ItemDisplayScreen(midlet, this, item);
                    Display.getDisplay(midlet).setCurrent(screen);
                }
            } catch (Exception e) {
                midlet.reportException(e, this);
            }
        } else if (command == syncCommand) {
            try {
                b = new boolean[size()];
                int csel = getSelectedFlags(b);
                if( csel < 1 ) {
                    Alert alert = new Alert("Error", "Please select at least one item to upload.", null, AlertType.ERROR);
                    alert.setTimeout(Alert.FOREVER);
                    Display.getDisplay(midlet).setCurrent(alert, this);
                    return;
                }
                
                //need to reuse & also implement RMS
                System.out.println(midlet.guser+":"+midlet.gpass);
                if( !midlet.guser.equals("") && !midlet.gpass.equals("") ) {
                    syncGoogleContacts();
                    return;
                }
                final TextField ut = new TextField( "Username:", midlet.guser, 128, TextField.EMAILADDR );
                final TextField pt = new TextField( "Password:", midlet.gpass, 128, TextField.PASSWORD );
                final Command okCommand = new Command("OK", Command.OK, 1);
                final Command cancelCommand = new Command("Cancel", Command.CANCEL, 1);
                Form form = new Form("Enter Google credentials", new TextField[]{ut, pt});
                form.addCommand(okCommand);
                form.addCommand(cancelCommand);
                form.setCommandListener(new CommandListener() {
                    public void commandAction(Command command, Displayable d) {
                        if (command == okCommand) {
                            midlet.guser = ut.getString(); midlet.gpass = pt.getString();
                            if( midlet.guser.equals("") || midlet.gpass.equals("") )
                                return;
                            syncGoogleContacts();
                        }
                        Display.getDisplay(midlet).setCurrent(ItemSelectionScreen.this);
                        System.out.println(midlet.guser+":"+midlet.gpass);
                    }
                });
                Display.getDisplay(midlet).setCurrent(form);
                
                
                
                //System.out.println("count = " + csel);
                
                
//                PIMItem item = (PIMItem) itemList.elementAt(getSelectedIndex());
//                Displayable screen = new ItemDisplayScreen(midlet, this, item);
//                Display.getDisplay(midlet).setCurrent(screen);
            } catch (Exception e) {
                midlet.reportException(e, this);
            }
        } else if (command == removeCommand) {
            try {
                
                b = new boolean[size()];
                int csel = getSelectedFlags(b);
                if( csel < 1 ) {
                    Alert alert = new Alert("Error", "Please select at least one item to delete.", null, AlertType.ERROR);
                    alert.setTimeout(Alert.FOREVER);
                    Display.getDisplay(midlet).setCurrent(alert, this);
                    return;
                }
                for( int i = 0; i < b.length; i++ ) {
                    //System.out.println("isSelected(" + i + ") = " + b[i]);
                    if( !b[i] )
                        continue;
                    PIMItem item = (PIMItem) itemList.elementAt(i);
                    switch (listType) {
                        case PIM.CONTACT_LIST:
                            ((ContactList) list).removeContact((Contact) item);
                            break;
                        case PIM.EVENT_LIST:
                            ((EventList) list).removeEvent((Event) item);
                            break;
                        case PIM.TODO_LIST:
                            ((ToDoList) list).removeToDo((ToDo) item);
                            break;
                    }
                }
                populateList();
            } catch (Exception e) {
                midlet.reportException(e, this);
            }
        } else if (command == newCommand) {
            try {
                PIMItem item = null;
                switch (listType) {
                    case PIM.CONTACT_LIST:
                        item = ((ContactList) list).createContact();
                        break;
                    case PIM.EVENT_LIST:
                        item = ((EventList) list).createEvent();
                        break;
                    case PIM.TODO_LIST:
                        item = ((ToDoList) list).createToDo();
                        break;
                }
                int fieldCode = getDisplayedFieldCode();
                item.addString(fieldCode, PIMItem.ATTR_NONE, "");
                Displayable screen = new ItemDisplayScreen(midlet, this, item);
                Display.getDisplay(midlet).setCurrent(screen);
            } catch (Exception e) {
                midlet.reportException(e, this);
            }
        }
    }
    
    private void syncGoogleContacts() {         //try to reuse
        new Thread(new Runnable() {
            public void run() {
                String ret = "";
                for( int i = 0; i < b.length; i++ ) {
                    //System.out.println("isSelected(" + i + ") = " + b[i]);
                    if( !b[i] )
                        continue;
                    PIMItem item = (PIMItem) itemList.elementAt(i);
                    name = "";
                    if( item.getPIMList().isSupportedField(Contact.FORMATTED_NAME) )
                        if( item.countValues(Contact.FORMATTED_NAME)!=0 )
                            name = item.getString(Contact.FORMATTED_NAME, 0);
                    if( item.getPIMList().isSupportedField(Contact.NAME) )
                        if( item.countValues(Contact.NAME)!=0 )
                            name = joinStringArray( item.getStringArray(Contact.NAME, 0) );
                    
                    phone = "";
                    if( item.getPIMList().isSupportedField(Contact.TEL) )
                        if( item.countValues(Contact.TEL)!=0 )
                            phone = item.getString(Contact.TEL, 0);
                    
                    email = "";
                    if( item.getPIMList().isSupportedField(Contact.EMAIL) )
                        if( item.countValues(Contact.EMAIL)!=0 )
                            email = item.getString(Contact.EMAIL, 0);
                    
                    param = "username=" + midlet.guser + "&password=" + midlet.gpass + "&name=" + name + "&phone=" + phone + "&email=" + email;
                    System.out.println("param="+param);
                    //System.out.println("test = " + item.getString(Contact.TEL, 1));
                    //System.out.println("name="+name+",tel="+phone+",email="+email);
                    
                    ret += midlet.sendHttpPost(param) + "\n";
                }
                Alert a = new Alert("Done", ret, null, AlertType.INFO);
                a.setTimeout(Alert.FOREVER);
                Display.getDisplay(midlet).setCurrent(a, ItemSelectionScreen.this);
                
            }
        }).start();
    }
    
    private String joinStringArray(String[] a) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < a.length; i++) {
            if (a[i] != null && a[i].length() > 0) {
                if (sb.length() > 0) {
                    sb.append(" ");     //change: here was a comma
                }
                sb.append(a[i]);
            }
        }
        return sb.toString();
    }
    
    int getDisplayedFieldCode() {
        int fieldCode = 0;
        switch (listType) {
            case PIM.CONTACT_LIST:
                fieldCode = Contact.FORMATTED_NAME;
                break;
            case PIM.EVENT_LIST:
                fieldCode = Event.SUMMARY;
                break;
            case PIM.TODO_LIST:
                fieldCode = ToDo.SUMMARY;
                break;
        }
        return fieldCode;
    }
    
    void fixDisplayedField(PIMItem item) {
        int fieldCode = getDisplayedFieldCode();
        if (listType == PIM.CONTACT_LIST) {
            boolean defined = false;
            if (item.countValues(fieldCode) != 0) {
                String s = item.getString(fieldCode, 0);
                if (s != null && s.trim().length() > 0) {
                    defined = true;
                }
            }
            if (!defined) {
                // try to fill in the values from NAME
                if (item.countValues(Contact.NAME) != 0) {
                    String[] a = item.getStringArray(Contact.NAME, 0);
                    if (a != null) {
                        StringBuffer sb = new StringBuffer();
                        if (a[Contact.NAME_GIVEN] != null) {
                            sb.append(a[Contact.NAME_GIVEN]);
                        }
                        if (a[Contact.NAME_FAMILY] != null) {
                            if (sb.length() > 0) {
                                sb.append(" ");
                            }
                            sb.append(a[Contact.NAME_FAMILY]);
                        }
                        String s = sb.toString().trim();
                        if (s.length() > 0) {
                            if (item.countValues(fieldCode) == 0) {
                                item.addString(fieldCode, Contact.ATTR_NONE, s);
                            } else {
                                item.setString(fieldCode, 0, Contact.ATTR_NONE, s);
                            }
                        }
                    }
                }
            }
        }
    }
    
    String getDisplayedField(PIMItem item) {
        int fieldCode = getDisplayedFieldCode();
        fixDisplayedField(item);
        String fieldValue = null;
        if (item.countValues(fieldCode) != 0) {
            String s = item.getString(fieldCode, 0);
            if (s != null && s.trim().length() != 0) {
                fieldValue = s;
            }
        }
        return fieldValue;
    }
    
}
